package com.situ.onlinebookstore.back.interceptor;

import com.situ.onlinebookstore.back.service.AdminService;
import com.situ.onlinebookstore.common.entity.Admin;
import com.situ.onlinebookstore.common.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {
    private final AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否已经登录
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (admin == null) {
            // 如果用户有自动登录，需要进行自动登录
            Cookie[] cookies = request.getCookies();
            Admin autoAdmin = new Admin();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("username")) {
                        autoAdmin.setUsername(cookie.getValue());
                    } else if (cookie.getName().equals("password")) {
                        autoAdmin.setPassword(cookie.getValue());
                    }
                }
            }
            //自动登录
            autoAdmin = adminService.autoLogin(autoAdmin);
            if (autoAdmin != null) {
                //成功 保存登录信息
                request.getSession().setAttribute("admin", autoAdmin);
                //更新登录用户
                admin = autoAdmin;

            }
        }
        if (admin == null) {
            //没登录
            //如果用户有自动登录，需要进行自动登录
            if (request.getRequestURI().endsWith("login.html")) {
                return true;
            }
            //跳转到登录页面 如果是页面请求则跳转登录界面
            else if (request.getRequestURI().endsWith(".html")) {
                response.sendRedirect("/html/admin/login.html");
            } else {
                //如果是ajax请求，则返回result
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(Result.error(5, "用户未登录，请登录后操作！").toJson());

            }
            //拦截返回false
            return false;
        } else {
            //登录了
            if (request.getRequestURI().endsWith("login.html")) {
                response.sendRedirect("/html/index.html");
                return false;
            }
            //放行返回true，拦截返回false
            return true;

        }

    }
}
